<template>
  <div class="book-list">
    <div class="search">
      <el-input
        placeholder="请输入书籍名称"
        v-model="searchText"
        clearable
        @clear="handleClear"
        @keyup.enter.native="handleSearch"
      >
        <el-button
          slot="append"
          icon="el-icon-search"
          @click="handleSearch"
        ></el-button>
      </el-input>
      <el-button type="primary" icon="el-icon-plus" @click="handleAdd"
        >添加书籍</el-button
      >
    </div>
    <el-table :data="books" style="width: 100%">
      <el-table-column prop="name" label="书籍名称"></el-table-column>
      <el-table-column prop="link" label="书籍图片">
        <template slot-scope="scope">
          <el-image
            :src="scope.row.link"
            :preview-src-list="[scope.row.link]"
            style="width: 80px; height: 80px"
          >
          </el-image>
        </template>
      </el-table-column>
      <el-table-column prop="publish_house" label="出版社"></el-table-column>
      <el-table-column prop="amount" label="数量"></el-table-column>
      <el-table-column prop="price" label="价格"></el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button type="primary" size="small" @click="handleEdit(scope.row)"
            >编辑</el-button
          >
          <el-button type="danger" size="small" @click="deleteBook(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      small
      background
      layout="prev, pager, next, jumper"
      :total="sourceBooks.length"
      :page-size="pageSize"
      :current-page="1"
      :pager-count="pageSize"
      class="result-list-pagination"
      @current-change="paginationChangeHandler"
    ></el-pagination>
    <!-- 添加和编辑数据弹框 -->
    <el-dialog
      :visible.sync="dialogVisible"
      title="添加书籍"
      :append-to-body="true"
    >
      <el-form :model="book" :rules="rules" ref="bookForm" label-width="160px">
        <el-form-item label="书籍名称" prop="name">
          <el-input v-model="book.name"></el-input>
        </el-form-item>
        <el-form-item label="书籍图片链接" prop="link">
          <el-input v-model="book.link"></el-input>
        </el-form-item>
        <el-form-item label="书籍出版社" prop="publish_house">
          <el-input v-model="book.publish_house"></el-input>
        </el-form-item>
        <el-form-item label="书籍价格" prop="price">
          <el-input v-model="book.price"></el-input>
        </el-form-item>
        <el-form-item label="书籍数量" prop="amount">
          <el-input v-model="book.amount"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSave">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      pageSize: 5, // 每页展示数量
      searchText: '',
      books: [],
      sourceBooks: [],
      dialogVisible: false, // 控制添加/编辑书籍他弹窗可见性
      isEdit: false, // 是否是编辑状态
      book: {
        name: '',
        link: '',
        publish_house: '',
        price: '',
        amount: '',
      },
      rules: {
        name: [{ required: true, message: '请输入书籍名称', trigger: 'blur' }],
        link: [
          { required: true, message: '请输入书籍图片链接', trigger: 'blur' },
        ],
        publish_house: [
          { required: true, message: '请输入书籍出版社', trigger: 'blur' },
        ],
        price: [{ required: true, message: '请输入书籍数量', trigger: 'blur' }],
        amount: [
          { required: true, message: '请输入书籍价格', trigger: 'blur' },
        ],
      },
    };
  },
  methods: {
    /**
     * 获取所有书籍
     */
    async getBookList() {
      const res = await axios.get('/api/booklist');
      if (res?.data.code === 0) {
        console.log('书籍列表：', res.data);
        // this.books = res.data.data;
        this.sourceBooks = res.data.data;

        // 获取第一页的数据
        this.paginationChangeHandler(1);
      } else {
        this.$message.error('获取书籍列表失败');
      }
    },
    /**
     * 添加书籍
     */
    async addBook() {
      const res = await axios.post('/api/addbook', this.book);
      if (res?.data.code === 0) {
        this.$message.success(res.data.msg);

        // 添加成功后，重新获取所有书籍，刷新界面
        this.getBookList();
      } else {
        this.$message.error('获取书籍列表失败');
      }
    },
    /**
     * 更新书籍
     */
    async updateBook() {
      const res = await axios.post('/api/updatebook', this.book);
      if (res?.data.code === 0) {
        this.$message.success(res.data.msg);

        // 更新成功后，重新获取所有书籍，刷新界面
        this.getBookList();
      } else {
        this.$message.error('更新书籍失败');
      }
    },
    /**
     * 更新书籍
     */
    async deleteBook(row) {
      const res = await axios.post('/api/deletebook', row);
      if (res?.data.code === 0) {
        this.$message.success(res.data.msg);
        // 删除成功后，重新获取所有书籍，刷新界面
        this.getBookList();
      } else {
        this.$message.error('删除书籍失败');
      }
    },
    async searchBook(keyword) {
      const res = await axios.get(`/api/searchbook?name=${keyword}`);
      if (res?.data.code === 0) {
        this.sourceBooks = res.data.data;
        this.paginationChangeHandler(1);
      } else {
      }
    },
    /**
     * 搜索书籍
     */
    handleSearch() {
      // 搜索书籍
      this.searchBook(this.searchText);
    },
    handleClear() {
      this.searchText = '';
    },
    /**
     * 处理添加书籍按钮
     */
    handleAdd() {
      this.dialogVisible = true;
      this.isEdit = false;
    },
    /**
     * 处理编辑书籍按钮
     */
    handleEdit(row) {
      this.book = Object.assign({}, row);
      this.dialogVisible = true;
      this.isEdit = true;
    },
    /**
     * 处理删除书籍按钮
     */
    handleDelete(row) {
      const index = this.books.findIndex(item => item.id === row.id);
      this.books.splice(index, 1);
    },
    async handleSave() {
      this.$refs.bookForm.validate(async valid => {
        if (valid) {
          if (this.isEdit) {
            await this.updateBook();
          } else {
            await this.addBook();
          }
          // 关闭弹窗
          this.dialogVisible = false;
        }
      });
    },
    /**
     * 分页
     */
    paginationChangeHandler(pageIndex) {
      const { pageSize } = this;
      this.books = this.sourceBooks.slice(
        (pageIndex - 1) * pageSize,
        pageIndex * pageSize
      );
      console.log(this.books);
      console.log(this.sourceBooks);
    },
  },
  async mounted() {
    console.log('页面加载完成');
    // 查询所有书籍
    await this.getBookList();
  },
};
</script>

<style>
.book-list {
  height: 100%;
}

.search {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.el-table__body-wrapper {
  overflow: auto;
  height: calc(100% - 120px);
}

.dialog-footer {
  text-align: center;
}
</style>
